<template>
  <div class="p-2">
    <el-card shadow="never">
      <!-- 搜索表单 -->
      <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="80px">
        <el-form-item label="真实姓名" prop="realName">
          <el-input
            v-model="queryParams.realName"
            placeholder="请输入真实姓名"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="审核状态" prop="authStatus">
          <el-select v-model="queryParams.authStatus" placeholder="请选择审核状态" clearable style="width: 200px">
            <el-option v-for="dict in beauty_auth_status" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 工具栏 -->
      <el-row :gutter="10" class="mb-4">
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="Check"
            :disabled="multiple"
            @click="handleBatchPass"
            v-hasPermi="['beauty:userAuth:audit']"
          >批量通过</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="Close"
            :disabled="multiple"
            @click="handleBatchReject"
            v-hasPermi="['beauty:userAuth:audit']"
          >批量拒绝</el-button>
        </el-col>
      </el-row>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="authList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="真实姓名" align="center" prop="realName" width="100" />
        <el-table-column label="证件类型" align="center" prop="docType" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.docType === 'idcard'" type="primary">身份证</el-tag>
            <el-tag v-else-if="scope.row.docType === 'passport'" type="success">护照</el-tag>
            <el-tag v-else type="info">未知</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="证件号码" align="center" width="180">
          <template #default="scope">
            {{ scope.row.docType === 'passport' ? scope.row.passportNo : scope.row.idCard }}
          </template>
        </el-table-column>
        <el-table-column label="认证材料" align="center" width="120">
          <template #default="scope">
            <el-button
              link
              type="primary"
              icon="View"
              @click="handleViewImages(scope.row)"
            >查看</el-button>
          </template>
        </el-table-column>
        <el-table-column label="审核状态" align="center" prop="authStatus" width="100">
          <template #default="scope">
            <dict-tag :options="beauty_auth_status" :value="scope.row.authStatus" />
          </template>
        </el-table-column>
        <el-table-column label="审核备注" align="center" prop="auditRemark" show-overflow-tooltip />
        <el-table-column label="提交时间" align="center" prop="createTime" width="160" />
        <el-table-column label="审核时间" align="center" prop="auditTime" width="160" />
        <el-table-column label="操作" align="center" fixed="right" width="200">
          <template #default="scope">
            <el-button
              link
              type="primary"
              icon="View"
              @click="handleDetail(scope.row)"
              v-hasPermi="['beauty:userAuth:query']"
            >详情</el-button>
            <template v-if="scope.row.authStatus === '1'">
              <el-button
                link
                type="success"
                @click="handleAudit(scope.row, '2')"
                v-hasPermi="['beauty:userAuth:audit']"
              >通过</el-button>
              <el-button
                link
                type="danger"
                @click="handleAudit(scope.row, '3')"
                v-hasPermi="['beauty:userAuth:audit']"
              >拒绝</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 审核对话框 -->
    <el-dialog :title="auditDialog.title" v-model="auditDialog.visible" width="500px" append-to-body>
      <el-form ref="auditFormRef" :model="auditForm" :rules="auditRules" label-width="100px">
        <el-form-item label="审核结果" prop="authStatus">
          <el-radio-group v-model="auditForm.authStatus">
            <el-radio v-for="dict in beauty_auth_status" :key="dict.value" :value="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核备注" prop="auditRemark">
          <el-input
            v-model="auditForm.auditRemark"
            type="textarea"
            :rows="4"
            placeholder="请输入审核备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="auditDialog.visible = false">取 消</el-button>
          <el-button type="primary" @click="submitAudit">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog title="认证详情" v-model="detailDialog.visible" width="800px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="认证ID">{{ detailDialog.data.authId }}</el-descriptions-item>
        <el-descriptions-item label="用户ID">{{ detailDialog.data.userId }}</el-descriptions-item>
        <el-descriptions-item label="用户手机">{{ detailDialog.data.userPhone }}</el-descriptions-item>
        <el-descriptions-item label="真实姓名">{{ detailDialog.data.realName }}</el-descriptions-item>
        <el-descriptions-item label="证件类型">
          <el-tag v-if="detailDialog.data.docType === 'idcard'" type="primary">身份证</el-tag>
          <el-tag v-else-if="detailDialog.data.docType === 'passport'" type="success">护照</el-tag>
          <el-tag v-else type="info">未知</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="证件号码">
          {{ detailDialog.data.docType === 'passport' ? detailDialog.data.passportNo : detailDialog.data.idCard }}
        </el-descriptions-item>
        <el-descriptions-item label="审核状态">
          <dict-tag :options="beauty_auth_status" :value="detailDialog.data.authStatus" />
        </el-descriptions-item>
        <el-descriptions-item label="提交时间">{{ detailDialog.data.createTime }}</el-descriptions-item>
        <el-descriptions-item label="审核时间">{{ detailDialog.data.auditTime }}</el-descriptions-item>
        <el-descriptions-item label="审核备注" :span="2">{{ detailDialog.data.auditRemark }}</el-descriptions-item>
      </el-descriptions>
      <el-divider>认证材料</el-divider>
      <div class="auth-images">
        <div v-for="(image, index) in detailDialog.images" :key="index" class="image-item">
          <div class="image-label">{{ image.label }}</div>
          <el-image
            :src="image.url"
            :preview-src-list="detailDialog.images.map(img => img.url)"
            fit="cover"
            style="width: 200px; height: 200px"
          />
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialog.visible = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看图片对话框 -->
    <el-dialog title="认证材料" v-model="imageDialog.visible" width="900px" append-to-body>
      <div class="auth-images">
        <div v-for="(image, index) in imageDialog.images" :key="index" class="image-item">
          <div class="image-label">{{ image.label }}</div>
          <el-image
            :src="image.url"
            :preview-src-list="imageDialog.images.map(img => img.url)"
            fit="cover"
            style="width: 200px; height: 200px"
          />
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="imageDialog.visible = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="BeautyUserAuth">
import { ref, reactive, getCurrentInstance } from 'vue';
import type { ComponentInternalInstance } from 'vue';
import { ElForm, ElMessageBox, ElMessage } from 'element-plus';
import { listUserAuth, getUserAuth, auditUserAuth, batchPassUserAuth, batchRejectUserAuth } from '@/api/beauty/userAuth';
import type { UserAuthQuery, UserAuthVO, AuditRequest } from '@/api/beauty/userAuth';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { beauty_auth_status } = toRefs<any>(proxy?.useDict('beauty_auth_status'));

const loading = ref(true);
const ids = ref<number[]>([]);
const multiple = ref(true);
const total = ref(0);
const authList = ref<UserAuthVO[]>([]);

const queryFormRef = ref<InstanceType<typeof ElForm>>();
const auditFormRef = ref<InstanceType<typeof ElForm>>();

const queryParams = ref<UserAuthQuery>({
  pageNum: 1,
  pageSize: 10,
  realName: undefined,
  authStatus: undefined
});

const auditDialog = reactive({
  visible: false,
  title: ''
});

interface ImageItem {
  label: string;
  url: string;
}

const detailDialog = reactive({
  visible: false,
  data: {} as UserAuthVO,
  images: [] as ImageItem[]
});

const imageDialog = reactive({
  visible: false,
  images: [] as ImageItem[]
});

const auditForm = ref<AuditRequest>({
  authId: 0,
  authStatus: '2',
  auditRemark: ''
});

const auditRules = reactive({
  authStatus: [
    { required: true, message: '请选择审核结果', trigger: 'change' }
  ]
});

// 查询认证列表
function getList() {
  loading.value = true;
  listUserAuth(queryParams.value).then((response: any) => {
    authList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 搜索按钮操作
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

// 重置按钮操作
function resetQuery() {
  queryFormRef.value?.resetFields();
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection: UserAuthVO[]) {
  ids.value = selection.map(item => item.authId);
  multiple.value = !selection.length;
}

// 审核操作
function handleAudit(row: UserAuthVO, status: string) {
  auditForm.value = {
    authId: row.authId,
    authStatus: status,
    auditRemark: ''
  };
  auditDialog.visible = true;
  auditDialog.title = status === '2' ? '审核通过' : '审核拒绝';
}

// 提交审核
function submitAudit() {
  auditFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      auditUserAuth(auditForm.value).then(() => {
        ElMessage.success('审核成功');
        auditDialog.visible = false;
        getList();
      });
    }
  });
}

// 批量通过
function handleBatchPass() {
  ElMessageBox.confirm('是否确认批量通过选中的认证申请？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info'
  }).then(() => {
    return batchPassUserAuth(ids.value);
  }).then(() => {
    getList();
    ElMessage.success('批量通过成功');
  });
}

// 批量拒绝
function handleBatchReject() {
  ElMessageBox.prompt('请输入拒绝原因', '批量拒绝', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /.+/,
    inputErrorMessage: '拒绝原因不能为空'
  }).then(({ value }) => {
    return batchRejectUserAuth(ids.value, value);
  }).then(() => {
    getList();
    ElMessage.success('批量拒绝成功');
  });
}

// 详情按钮操作
function handleDetail(row: UserAuthVO) {
  getUserAuth(row.authId).then((response: any) => {
    detailDialog.data = response.data;

    // 根据证件类型构建图片列表
    const images: ImageItem[] = [];
    const data = response.data;

    if (data.docType === 'idcard') {
      // 身份证
      if (data.idCardFront) {
        images.push({ label: '身份证人像面', url: data.idCardFront });
      }
      if (data.idCardBack) {
        images.push({ label: '身份证国徽面', url: data.idCardBack });
      }
    } else if (data.docType === 'passport') {
      // 护照
      if (data.passportPhoto) {
        images.push({ label: '护照资料页', url: data.passportPhoto });
      }
    }

    // 手持证件照（通用）
    if (data.faceImage) {
      const label = data.docType === 'passport' ? '手持护照照片' : '手持身份证照片';
      images.push({ label, url: data.faceImage });
    }

    detailDialog.images = images;
    detailDialog.visible = true;
  });
}

// 查看图片
function handleViewImages(row: UserAuthVO) {
  // 根据证件类型构建图片列表
  const images: ImageItem[] = [];

  if (row.docType === 'idcard') {
    // 身份证
    if (row.idCardFront) {
      images.push({ label: '身份证人像面', url: row.idCardFront });
    }
    if (row.idCardBack) {
      images.push({ label: '身份证国徽面', url: row.idCardBack });
    }
  } else if (row.docType === 'passport') {
    // 护照
    if (row.passportPhoto) {
      images.push({ label: '护照资料页', url: row.passportPhoto });
    }
  }

  // 手持证件照（通用）
  if (row.faceImage) {
    const label = row.docType === 'passport' ? '手持护照照片' : '手持身份证照片';
    images.push({ label, url: row.faceImage });
  }

  imageDialog.images = images;
  imageDialog.visible = true;
}

// 导出按钮操作
function handleExport() {
  ElMessageBox.confirm('是否确认导出所有认证数据项？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // TODO: 实现导出功能
    ElMessage.success('导出成功');
  });
}

getList();
</script>

<style scoped>
.auth-images {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  gap: 20px;
}

.image-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.image-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
  font-weight: 500;
}
</style>
